/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.DisLockUser;
import me.zhengjie.modules.web.service.mybatisplus.IDisLockUserPlusService;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.DisLockUserRepository;
import me.zhengjie.modules.system.service.DisLockUserService;
import me.zhengjie.modules.system.service.dto.DisLockUserDto;
import me.zhengjie.modules.system.service.dto.DisLockUserQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.DisLockUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author 王宇
* @date 2024-01-16
**/
@Service
@RequiredArgsConstructor
public class DisLockUserServiceImpl implements DisLockUserService {

    private final DisLockUserRepository disLockUserRepository;
    private final DisLockUserMapper disLockUserMapper;

    @Autowired
    private IDisLockUserPlusService disLockUserPlusService;

    @Override
    public Map<String,Object> queryAll(DisLockUserQueryCriteria criteria, Pageable pageable){
        Page<DisLockUser> page = disLockUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(disLockUserMapper::toDto));
    }

    @Override
    public List<DisLockUserDto> queryAll(DisLockUserQueryCriteria criteria){
        return disLockUserMapper.toDto(disLockUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DisLockUserDto findById(String lockId) {
        DisLockUser disLockUser = disLockUserRepository.findById(lockId).orElseGet(DisLockUser::new);
        ValidationUtil.isNull(disLockUser.getLockId(),"DisLockUser","lockId",lockId);
        return disLockUserMapper.toDto(disLockUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DisLockUserDto create(DisLockUser resources) {
        resources.setLockId(IdUtil.simpleUUID());
        resources.setCreateTime(DateUtil.TimestampNow());
        resources.setCreateUser(SecurityUtils.getCurrentUsername());
        resources.setLockStatus(ConstantUtils.Valid);
        LambdaQueryWrapper<DisLockUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DisLockUser::getLockStatus, ConstantUtils.Valid);
        List<DisLockUser> list = disLockUserPlusService.list(wrapper);
        if (CollectionUtils.isEmpty(list)){
            return disLockUserMapper.toDto(disLockUserRepository.save(resources));
        }else {
            DisLockUser disLockUser = list.get(0);
            LambdaQueryWrapper<DisLockUser> lockUserWrapper = new LambdaQueryWrapper<>();
            lockUserWrapper.eq(DisLockUser::getLockId,disLockUser.getLockId());
            DisLockUser entity = new DisLockUser();
            entity.setLockStatus(ConstantUtils.InValid);
            disLockUserPlusService.update(entity,lockUserWrapper);
            return disLockUserMapper.toDto(disLockUserRepository.save(resources));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DisLockUser resources) {
        DisLockUser disLockUser = disLockUserRepository.findById(resources.getLockId()).orElseGet(DisLockUser::new);
        ValidationUtil.isNull( disLockUser.getLockId(),"DisLockUser","id",resources.getLockId());
        disLockUser.copy(resources);
        disLockUserRepository.save(disLockUser);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String lockId : ids) {
            disLockUserRepository.deleteById(lockId);
        }
    }

    @Override
    public void download(List<DisLockUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DisLockUserDto disLockUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("创建人", disLockUser.getCreateUser());
            map.put("创建时间", disLockUser.getCreateTime());
            map.put("时间", disLockUser.getLockMonth());
            map.put("状态0：无效，1：有效，-1：删除", disLockUser.getLockStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}